package com.frame.filter

import com.app.security.MyUsernamePasswordToken
import com.fasterxml.jackson.databind.ObjectMapper
import org.apache.shiro.authc.AuthenticationException
import org.apache.shiro.authc.AuthenticationToken
import org.apache.shiro.subject.Subject
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter
import org.apache.shiro.web.util.WebUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory

import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * Created by three on 14-8-8.
 */
class MyBasicHttpAuthFilter extends BasicHttpAuthenticationFilter {

    private static final Logger log = LoggerFactory.getLogger(MyBasicHttpAuthFilter.class);
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if((request as HttpServletRequest).getMethod()=='OPTIONS') {
            return true
        }
        try {
            request.setAttribute("loginError", null);
            return super.onAccessDenied(request, response)
        } catch (Exception e) {
            request.setAttribute("loginError", e)
        }
        return true;

    }

    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e,
                                     ServletRequest request, ServletResponse response) {
        request.setAttribute("loginError", e)
        return true;
    }
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String authorizationHeader = getAuthzHeader(request);
        if (authorizationHeader == null || authorizationHeader.length() == 0) {
            // Create an empty authentication token since there is no
            // Authorization header.
            return createToken("", "", request, response);
        }

        if (log.isDebugEnabled()) {
            log.debug("Attempting to execute login with headers [" + authorizationHeader + "]");
        }

        String[] prinCred = getPrincipalsAndCredentials(authorizationHeader, request);
        if (prinCred == null || prinCred.length < 2) {
            // Create an authentication token with an empty password,
            // since one hasn't been provided in the request.
            String username = prinCred == null || prinCred.length == 0 ? "" : prinCred[0];
            return createToken(username, "", request, response);
        }
        String captcha = WebUtils.getCleanParam(request,"vaildCode");
        String username = prinCred[0];
        String password = prinCred[1];
        boolean rememberMe = isRememberMe(request);
        String host = getHost(request);
        return new MyUsernamePasswordToken(username,password.toCharArray(), rememberMe, host, captcha);;
    }

}
